package com.example.springboottest.example.awss3;

import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.concurrent.TimeUnit;

public class S3FileService {
    private AmazonS3 client;

    public S3FileService(AmazonS3 client) {
        this.client = client;
    }

    /**
     * 执行文件上传
     *
     * @param file   要上传的文件的路径
     * @param key    存储文件的路径
     * @param bucket 桶名
     * @return 文件路径
     */
    public String upload(File file, String key, String bucket) {
        client.putObject(new PutObjectRequest(bucket, key, file).withCannedAcl(CannedAccessControlList.PublicRead));
        GeneratePresignedUrlRequest urlRequest = new GeneratePresignedUrlRequest(bucket, key);
        URL url = client.generatePresignedUrl(urlRequest);
        return url.toString();
    }

    /**
     * 文件流上传
     *
     * @param input
     * @param key
     * @param bucket 桶名
     * @return
     * @throws IOException
     */
    public String upload(InputStream input, String key, String bucket) throws IOException {
        Date expireDate = new Date(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(30));
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setHttpExpiresDate(expireDate);
        metadata.setContentLength(input.available());

        client.putObject(new PutObjectRequest(bucket, key, input, metadata).withCannedAcl(CannedAccessControlList.PublicRead));
        GeneratePresignedUrlRequest urlRequest = new GeneratePresignedUrlRequest(bucket, key);
        URL url = client.generatePresignedUrl(urlRequest);
        return url.toString();
    }
}
